import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout, getUserInfo } from '../api/auth'
import router from '../router'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))

  const isLoggedIn = computed(() => !!token.value)

  // 判断用户是否为管理员
  const isAdmin = computed(() => userInfo.value.roleId === '1')

  // 判断用户是否为普通用户
  const isRegularUser = computed(() => userInfo.value.roleId === '2')

  // 检查用户是否有特定角色
  function hasRole(roleId) {
    return userInfo.value.roleId === roleId.toString()
  }

  // 登录
  async function loginAction(loginForm) {
    try {
      const res = await login(loginForm)
      token.value = res.data.token
      userInfo.value = {
        userId: res.data.userId,
        username: res.data.username,
        roleId: res.data.roleId,
        tenantId: res.data.tenantId
      }

      // 保存到本地存储
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return Promise.resolve(res)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 登出
  async function logoutAction() {
    try {
      await logout()
    } catch (error) {
      console.error('登出失败', error)
    } finally {
      // 清除状态和本地存储
      token.value = ''
      userInfo.value = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')

      // 重定向到登录页
      router.push('/login')
    }
  }

  // 获取用户信息
  async function fetchUserInfo() {
    if (!token.value) return

    try {
      const res = await getUserInfo()
      userInfo.value = res.data
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    isAdmin,
    isRegularUser,
    hasRole,
    loginAction,
    logoutAction,
    fetchUserInfo
  }
})
